<?php

namespace app\push\controller;

use think\Controller;
use think\worker\Server;
use \Workerman\Lib\Timer;
use think\Cache;

class Worker extends Server
{
    protected $socket = 'websocket://0.0.0.0:8080';


    public function init()
    {
        //新增加一个属性，用来保存uid到connection的映射(uid是用户ID或者客户端唯一标示)
        $this->worker->uidConnections=[];
    }

    /**
     * 收到信息
     * @param $connection
     * @param $data
     */
    public function onMessage($connection, $data)
    {
        //$connection->send($data);

        $data_array=json_decode($data,true);

      //  var_dump($data_array);

        if(!$data_array){
            return $connection->send(json_encode(ApiJson(0, '参数必须为JSON', [], [], 400)));
        }
        if (empty($data_array['sid'])) {
            $connection->send(json_encode(ApiJson(0, 'SID不存在', [], [], 400)));
            $connection->close();
            return false;
        }
        $sid = Cache::get($data_array['sid']);
        if (!$sid) {
            $connection->send(json_encode(ApiJson(0, '登录SID失效,unlogin', [], [], 100)));
            $connection->close();
            return false;
        }
        $connection->uid = $data_array['sid'];
        $connection->datas = $data_array;
        $connection->lastMessageTime=time();
        $this->worker->uidConnections[$connection->uid]=$connection;



    }

    /**
     * 当连接建立时触发的回调函数
     * @param $connection
     */
    public function onConnect($connection)
    {

        $connection->send("已建立连接");

    }

    /**
     * 当连接断开时触发的回调函数
     * @param $connection
     */
    public function onClose($connection)
    {
      /*  $time_id =   $this->worker->uidConnections[$connection->uid]->tim_id ;
        Timer::del($time_id);*/
        $connection->send(json_encode(ApiJson(0, '关闭成功', [], [], 250)));
        $connection->close();
        return false;
    }
    /**
     * 当客户端的连接上发生错误时触发
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        echo "error $code $msg\n";
    }
    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker)
    {
        echo "Worker starting.....\n";
    $timer_id=\Workerman\Lib\Timer::add(1,function()use($worker){
            $time_now=time();
            foreach ($this->worker->uidConnections as $key=>$connection){
                if(empty($connection->lastMessageTime)){
                    $connection->lastMessageTime=$time_now;
                    continue;
                }
                //上次通许时间间隔大于心跳间隔，则认为客户端已经掉线
                if($time_now-$connection->lastMessageTime>45){
                    $connection->send(json_encode(ApiJson(1, '无回复心跳或者无信息提交，连接关闭', [], [], 252)));
                    $connection->close();
                }
                //$connection->send(json_encode(ApiJson(0, '心跳,检测连接', [], [], 252)));
                if(isset($connection->datas)){
                    $data_array = $connection->datas;

                    if(isset($data_array['code'])){
                        if(is_array($data_array['code'])){
                            $res =  gethqMony($data_array['code']);
                        }else{
                            $res =  gethq($data_array['code']);
                        }
                    }elseif(isset($data_array['message'])&&$data_array['message']){
                                //获取小心的最新数据
                        $sid = $data_array['sid'];
                        $count = getMessageNums($sid);
                        $res = ["count"=>$count];
                    }elseif(isset($data_array['money'])&&$data_array['money']){
                                //处理用户资产
                        $sid = $data_array['sid'];
                        $res = getMoney($sid);//资产计算
                    }

                    $connection->send(json_encode(ApiJson(1, '查询成功', $res, [], 100)));
                }
            }
        },true);
        echo "Timer starting.... \n";
     //   echo 'Timer_id:'.$timer_id;

    }
}
